import os
import sys

from google.appengine.ext import db

from glog import AppEnv
from glog.base import Error

__all__ = ['AppConfig','getAppConfig']

class AppConfig(db.Model):
    HostURL = db.StringProperty(default=AppEnv.host)
    postsPerPage = db.IntegerProperty(default=20)
    rssCount = db.IntegerProperty(default=20)
    postsPerPageList = db.IntegerProperty(default=50)

def checkhosturl(s):
    s = s.rstrip('/')
    if not s.startswith('http://') and not s.startswith('https://'):
        s = 'http://'+s
    try:
        l = db.Link(s)
    except db.BadValueError:
        return False,'Host URL is Invalid'
    if s.rfind('/') > 6:
        return False,'Host URL is Invalid'
    return True,s

def checkAll(blogName, postsPerPage, rssCount, postsPerPageList, hostURL):
    cl = [
        checkhosturl(hostURL),
          ]
    return all([cr[0] for cr in cl]),[cr[1] for cr in cl]

__config__ = None
def getAppConfig(reload=False):
    global __config__
    """Get system config

    Args:
        reload: reload from DB other than from cache

    Returns:
        current system config
    """
    if not __config__ or reload:
        config = AppConfig.all().fetch(1)
        if not config:
            raise Error.AppNotInitializedError()
        else:
            config = config[0]
        __config__ = config
    return __config__
